package cs342.uwosh.group1.mycontacts;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import com.mycontacts.R;
import com.mycontacts.R.layout;
import com.mycontacts.R.menu;

import cs342.uwosh.group1.mycontacts.Threads.AsyncResponse;
import cs342.uwosh.group1.mycontacts.Threads.CreateUserOnCloud;
import cs342.uwosh.group1.mycontacts.Threads.VerifyLogin;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class LoginActivity extends Activity {
	public static int uid;
	SharedPreferences mPrefs;
	//VerifyLogin vLogin = new VerifyLogin();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		//vLogin.delegate = this;
		
		findViewById(R.id.skippy).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				skippy();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
		
		
	}
	
	public void skippy(){
		this.finish();
	}
	
	public void login(View view) throws InterruptedException{
		System.out.println("this");
		EditText u = (EditText)findViewById(R.id.username);
		System.out.println("this");
		EditText p = (EditText)findViewById(R.id.password);
		System.out.println("this");
		String user = u.getText().toString();
		System.out.println("this");
		String pass = p.getText().toString();
		System.out.println("this");
				
	 
		
		//new VerifyLogin().execute(user,pass);	
		//System.out.print("slfjslkdfjsdfls::::::  " + uid);	
		
		uid = doSomeShit(user,pass);		
		
		
		if(uid > 0){
			System.out.println(uid);
			mPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
		    
		    SharedPreferences.Editor edit = mPrefs.edit();
		    edit.putInt("uid", uid);
		    edit.putString("username", user);
		    edit.putString("password", pass);
		    edit.putInt("ver", -1);
		    edit.commit();
		    MainActivity.loggedIn = true;
			finish();
		}else{
			TextView i = (TextView)findViewById(R.id.invalid);
			i.setVisibility(TextView.VISIBLE);
		}
	}


	public void set(View view){
		Intent intent = new Intent(this, Setup.class);
		startActivity(intent);
		finish();
	}
	
	public int doSomeShit(String user, String pass){
		String username = user;
		String password = pass;
		
		URL url;
		String urlParameters = "?username='"+username+"'&password='"+password+"'";
		HttpURLConnection connection = null;
	
		try {
			//Setup connection
			url = new URL("http://softeng.cs.uwosh.edu/students/smithk58/project2/verifyLogin.php"+urlParameters);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
	        connection.setDoInput(true);
	        connection.setDoOutput(true);
	        connection.setUseCaches(false);
			
	        //Send request
	        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
	        wr.writeBytes(urlParameters);
	        wr.flush();
	        wr.close();
	        
	        //Get Response (should be the users id in this case, which needs to be stored in preferences)
	        InputStream is = connection.getInputStream();
	        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
	        String line;
	        StringBuffer response = new StringBuffer(); 
	        while((line = rd.readLine()) != null) {
	          response.append(line);
	         // response.append('\r');
	        }
	        rd.close();
	        System.out.println(response.toString());	        
	        return Integer.parseInt(response.toString());
	        
		} catch (MalformedURLException e) {
			//return "Bad URL";
			return -1;
		} catch (IOException e) {
			//return "Unable to retrieve web page";
			return -1;
		}
		finally
        {
            if(connection != null)
              connection.disconnect();
        }
		
		
	}
	
/*
	@Override
	public void processFinish(int output) {
		//this is the uid from VerifyLogin async
		uid = output;
	}*/
}